<template>
  <el-row>
    <el-col :span="8">
      <el-select placeholder="请选择省" v-model="data.provinceCode">
        <el-option
          v-for="province in provinceOptions"
          :key="province.value"
          :label="province.label"
          :value="province.value">
        </el-option>
      </el-select>
    </el-col>
    <el-col :span="9">
      <el-select placeholder="请选择市" v-model="data.cityCode">
        <el-option
          v-for="city in cityOptions"
          :key="city.value"
          :label="city.label"
          :value="city.value">
        </el-option>
      </el-select>
    </el-col>
    <el-col :span="7" v-if="!hideArea">
      <el-select placeholder="请选择区" v-model="data.areaCode">
        <el-option
          v-for="area in areaOptions"
          :key="area.value"
          :label="area.label"
          :value="area.value">
        </el-option>
      </el-select>
    </el-col>
  </el-row>
</template>

<script>
  import {regionData} from 'element-china-area-data'

  export default {
    name: 'dist-picker',
    props: {
      province: {type: String, default: ''},
      city: {type: String, default: ''},
      area: {type: String, default: ''},
      hideArea: {type: Boolean, default: false}
    },
    data() {
      return {
        provinceOptions: regionData,
        cityOptions: [],
        areaOptions: [],
        data: {
          provinceCode: this.province,
          cityCode: this.city,
          areaCode: this.area
        }
      }
    },
    watch: {
      'province': function () {
        this.data.provinceCode = this.province
      },
      'city': function () {
        this.data.cityCode = this.city
      },
      'area': function () {
        this.data.areaCode = this.area
      },
      'data.provinceCode': function () {
        let currentProvince = this.provinceOptions.find((province) => {
          return province.value === this.data.provinceCode
        })
        this.cityOptions = currentProvince.children
        this.data.cityCode = ''
        this.data.areaCode = ''
        this.areaOptions = []
        this.$emit('onSelected', this.data)
      },
      'data.cityCode': function () {
        let currentCity = this.cityOptions.find((city) => {
          return city.value === this.data.cityCode
        })
        this.areaOptions = currentCity.children
        this.data.areaCode = ''
        this.$emit('onSelected', this.data)
      },
      'data.areaCode': function () {
        this.$emit('onSelected', this.data)
      }
    }
  }
</script>
